import json
import random
from time import sleep

import requests
from redis import ConnectionPool, StrictRedis
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import traceback
from adsl import ADSL

class SimpleHash(object):
    def __init__(self, cap, seed):
        self.cap = cap
        self.seed = seed

    def hash(self, value):
        ret = 0
        for i in range(len(value)):
            ret += self.seed * ret + ord(value[i])
        return (self.cap - 1) & ret


class RedisClient(object):
    pool = ConnectionPool(**{
        'host': '129.211.169.177',
        'port': 6379,
        'db': 5,
        'password': 950218
    })
    client = StrictRedis(connection_pool=pool)

    def set_cookies(self, cookies):
        self.client.set('cookies', cookies)

    def get_cookies(self):
        return str(self.client.get('cookies'), encoding='utf-8')

    def set_ixueshu_cookies(self, cookies):
        self.client.set('ixueshu_cookies', cookies)

    def get_ixueshu_cookies(self):
        return str(self.client.get('ixueshu_cookies'), encoding='utf-8')

    def ADSL(self):
        key = 'adsl'
        try:
            data = self.client.hvals(key)
            if data is None:
                return None
            else:
                ip = random.choice(data)
                return str(ip.decode())
        except:
            return None

    def setADSL(self, data):
        self.client.hset('adsl_tianqi', str(data['expire']), f'{data["ip"]}:{data["port"]}')

    def getADSL(self):
        key = 'adsl_tianqi'
        try:
            keys = self.client.hkeys(key)
            if keys is None:
                return None
            else:
                selectkey = random.choice(keys)
                ip = self.client.hget(key, selectkey)
                return selectkey, str(ip.decode())
        except:
            return None


class IXueShu(object):
    starturl = 'https://www.ixueshu.com/clc/1.html?sort=downloads%20desc&page=1'
    url = 'https://www.ixueshu.com/document/2e1c32172b661dd898beecc80c47c671318947a18e7f9386.html'
    r = RedisClient()
    adsl =  ADSL()

    def requestLogin(self):
        try:
            headers = {
                "sec-ch-ua-platform": "macOS",
                "Upgrade-Insecure-Requests": "1",
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "Sec-Fetch-Site": "same-origin",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-User": "?1",
                "Sec-Fetch-Dest": "document",
                "Accept-Encoding": "gzip, deflate, br",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                "Referer": "https://www.ixueshu.com/",
                "x-dsa-host": "ixueshu.com",
                "x-dsa-originalip": "47.0.0.0",
                "x-dsa-secret": "DSA20130311X"
            }
            data = {
                'redirect': '/',
                'username': '17601253218',
                'password': '63505711'
            }
            try:
                key, adsl = self.r.getADSL()
            except:
                self.adsl.init(1)
                key, adsl = self.r.getADSL()
            proxies={}
            if adsl:
                proxies = {
                    'http': 'http://dujhre:4l9axcjk@' + adsl,
                    'https': 'http://dujhre:4l9axcjk@' + adsl,
                }
            try:
                r = requests.post('https://www.ixueshu.com/login.html', headers=headers, data=data, verify=False, proxies=proxies,timeout=10)
                print(r.status_code)
                if r.status_code == 200:
                    save_cookie = {}
                    cookies = r.cookies._cookies['.ixueshu.com']['/']
                    for key in cookies.keys():
                        save_cookie[cookies[key].name] = cookies[key].value
                    cookies302 = r.history[0].cookies._cookies['www.ixueshu.com']['/']
                    for key in cookies302.keys():
                        save_cookie[cookies302[key].name] = cookies302[key].value
                    self.r.set_ixueshu_cookies(json.dumps(save_cookie))
                    return 'success'
                elif r.status_code == 403:
                    self.adsl.DelOneAdsl(key)
                    self.adsl.reflash()
                    return 'error'
                else:
                    return 'error'
            except Exception as e:
                return 'error'
        except:
            return 'error'

    def login(self):
        chrome_options = Options()
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--headless')
        driver = webdriver.Chrome(options=chrome_options)
        driver.set_window_size(1920, 1080)
        try:
            driver.get('https://www.ixueshu.com')
            driver.implicitly_wait(10)
            driver.find_element_by_class_name('login_switch').click()
            driver.implicitly_wait(1)
            driver.find_element_by_id('username').send_keys('18202776458')
            driver.find_element_by_id('password').send_keys('63505711!')
            driver.find_element_by_css_selector('.login_btn>input').click()
            dictCookies = driver.get_cookies()
            jsonCookies = json.dumps(dictCookies)
            self.r.set_cookies(jsonCookies)
            driver.quit()
        except Exception as e:
            print(e)
            driver.quit()

if __name__ == '__main__':
    bot = IXueShu()
    while True:
        res = bot.requestLogin()
        if res == 'error':
            sleep(2)
        if res == 'success':
            sleep(2)
